﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace MASAS.MSM.SharePoint.REST.Utils
{

    /// <summary>
    /// Class SPListItem.
    /// </summary>
    internal class SPListItem
    {

        // Private members...

        private Dictionary<string, object> _values;

        // Public accessors...

        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>The identifier.</value>
        internal string ID { get; set; }

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        /// <value>The title.</value>
        internal string Title { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="System.Object"/> with the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>System.Object.</returns>
        internal object this[string key]
        {
            get { return _values[key]; }
            set { _values[key] = value; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SPListItem"/> class.
        /// </summary>
        /// <param name="parent">The parent.</param>
        internal SPListItem( SPList parent = null )
        {
            _values = new Dictionary<string, object>();

            if( parent != null )
            {
                Dictionary<string, object> metadata = new Dictionary<string, object>();
                metadata["type"] = parent.ListItemEntityType;
                _values["__metadata"] = metadata;
            }
        }

        /// <summary>
        /// Converts this object to a JSON string.
        /// </summary>
        /// <returns>System.String.</returns>
        internal string ToJSON()
        {
            string jsonStr = "";

            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            jsonStr = jsSerializer.Serialize( _values );


            return jsonStr;
        }

        /// <summary>
        /// Creates a SPListItem using the specified attributes.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        /// <returns>SPListItem.</returns>
        internal static SPListItem Create( Dictionary<string, object> attributes )
        {
            SPListItem listItem = new SPListItem();
            listItem._values = attributes;

            object tempObject;
            if( attributes.TryGetValue( "Title", out tempObject ) )
            {
                listItem.Title = tempObject as string;
            }
            if( attributes.TryGetValue( "ID", out tempObject ) )
            {
                listItem.ID = tempObject as string;
            }

            return listItem;
        }

    }

}
